import typescript from '@rollup/plugin-typescript'
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import postcss from 'rollup-plugin-postcss'
import alias from '@rollup/plugin-alias'
import path from 'path'
import fs from 'fs'
import { fileURLToPath } from 'url'

// 获取 __dirname 的 ES 模块等效值
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 动态获取项目入口
function getProjectEntries() {
  const projectsDir = 'src/projects'
  const entries = {}
  
  if (fs.existsSync(projectsDir)) {
    const projects = fs.readdirSync(projectsDir)
    projects.forEach(project => {
      const projectIndexPath = path.join(projectsDir, project, 'index.css')
      if (fs.existsSync(projectIndexPath)) {
        entries[`projects/${project}/index`] = projectIndexPath
      }
    })
  }
  
  return entries
}

// 动态获取base目录下的入口
function getBaseEntries() {
  const baseDir = 'src/base'
  const entries = {}
  
  if (fs.existsSync(baseDir)) {
    const baseDirs = fs.readdirSync(baseDir, { withFileTypes: true })
    baseDirs.forEach(dir => {
      if (dir.isDirectory()) {
        const indexPath = path.join(baseDir, dir.name, 'index.css')
        if (fs.existsSync(indexPath)) {
          entries[`base/${dir.name}`] = indexPath
        }
      }
    })
  }
  
  return entries
}

export default {
  input: {
    'index': 'src/index.ts',
    'base/index': 'src/base/index.ts',
    'styles/reset': 'src/base/styles/reset.css',
    'fonts/index': 'src/base/fonts/index.css',
    // 批量处理base入口
    ...getBaseEntries(),
    // 批量处理项目入口
    ...getProjectEntries()
  },
  output: [
    {
      dir: 'dist',
      format: 'cjs',
      sourcemap: true,
      entryFileNames: '[name].js',
      assetFileNames: '[name].[ext]',
      exports: 'named'
    },
    {
      dir: 'dist',
      format: 'esm',
      sourcemap: true,
      entryFileNames: '[name].mjs',
      assetFileNames: '[name].[ext]',
      exports: 'named'
    }
  ],
  plugins: [
    alias({
      entries: [
        { find: '@/', replacement: path.resolve(__dirname, 'src') + '/' },
        { find: '@base', replacement: path.resolve(__dirname, 'src/base') },
        { find: '@projects', replacement: path.resolve(__dirname, 'src/projects') }
      ]
    }),
    postcss({
      extract: true,
      modules: false,
      minimize: true,
      extensions: ['.css']
    }),
    resolve(),
    commonjs()
  ]
}